import React from 'react'
import {formatMoney} from "../utils/utils";
export default React.createClass({
    getInitialState: function () {
        return {};
    },
    value: '',
    render: function () {
        //有v属性,则是显示数字,因为我们的金额单位都是分,这里除100
        if (!this.props.input)
            return <span className={this.props.className}>{formatMoney(this.props.v/100 || 0)}{this.props.children}</span>
        //输入框
        return <input type="text" value={this.state.value || ''} maxLength="9" placeholder={this.props.placeholder}
                      className={this.props.className} onChange={this.change}/>
    },

    change: function (e) {
        let value = e.target.value;
        //限制输入,仅数字和小数点
        value = value.replace(/[^\d\.]/g, '')
        //首位截0,但可以输0.44
        value = value.replace(/^0+(?=[^\.])/g, '')
        //以.开头不允许
        value = value.replace(/^\./g, '')
        //小数点只允许出现一次
        value = value.replace(/(.+\.[^\.]*)\./g, '$1')
        //最多输入两位小数
        value = value.replace(/(.+\.\d{2}).+/g, '$1')

        if (this.props.onChange && value != this.state.value) {
            this.props.onChange(value);
        }
        this.value = value;
        this.setState({value})
    }
})